package com.OrderingSystem.service.impl;

import com.OrderingSystem.config.WechatAccountConfig;
import com.OrderingSystem.dto.OrderDTO;
import com.OrderingSystem.mapper.OrderMasterMapper;
import com.OrderingSystem.pojo.OrderMaster;
import com.OrderingSystem.service.PushMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class PushMessageServiceImpl implements PushMessageService {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatAccountConfig accountConfig;

    @Autowired
    OrderMasterMapper orderMasterMapper;

    @Override
    public void orderStatus(Integer orderId) {
        // 获取订单信息
        OrderMaster orderMaster = orderMasterMapper.selectById(orderId);

        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(accountConfig.getTemplateId());
        templateMessage.setToUser(orderMaster.getBuyerOpenid());

        Integer orderStatus = orderMaster.getOrderStatus();
        String words = "";
        if (orderStatus == 0){
            words = "下单成功";
        } else if (orderStatus == 1){
            words = "订单已完结";
        } else if (orderStatus == 2){
            words = "订单已取消";
        }
        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("first", "亲，您的订单下单成功"),
                new WxMpTemplateData("keyword1", "微信点餐"),
                new WxMpTemplateData("keyword2", "18868812345"),
                new WxMpTemplateData("keyword3", String.valueOf(orderMaster.getOrderId())),
                new WxMpTemplateData("keyword4", words),
                new WxMpTemplateData("keyword5", "￥" + orderMaster.getOrderAmount() + "元"),
                new WxMpTemplateData("remark", "谢谢惠顾，欢迎再次光临！")
        );
        templateMessage.setData(data);
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }catch (WxErrorException e) {
            log.error("【微信模版消息】发送失败, {}", e);
        }
    }
}